<template>
	<el-drawer style="padding: 0" v-model="configureVisible" :show-close="false" :destroy-on-close="true" size="100%">
		<template #header="{ close, titleId, titleClass }">
			<span :id="titleId" :class="titleClass">
				{{ state.queryForm.empiRuleInfoVersion ? '查看配置' : '配置字段' }}
				&nbsp;
				<el-button type="primary" @click="saveFields" v-if="!state.queryForm.empiRuleInfoVersion">保存配置</el-button>
			</span>
			<el-button class="btnReturn" @click="backVersion">返回</el-button>
		</template>
		<el-form :inline="true" :model="state.queryForm">
			<!-- <el-form-item>
				<el-input v-model="state.queryForm.fieldCode" placeholder="请输入字段名称"></el-input>
			</el-form-item>
			<el-form-item>
				<el-select style="width: 130px" v-model="state.queryForm.ifInvalid">
					<el-option label="开启" value="0">开启</el-option>
					<el-option label="关闭" value="1">关闭</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button :icon="Search" @click="searchEvent" type="primary">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button :icon="Refresh" @click="resets">重置</el-button>
			</el-form-item> -->
			<el-form-item v-if="!state.queryForm.empiRuleInfoVersion">
				<el-button :icon="Plus" type="primary" @click="addOrUpdateHandle('', 'add', {})">新增字段</el-button>
			</el-form-item>
			<el-form-item v-if="!state.queryForm.empiRuleInfoVersion">
				<el-button :icon="Delete" type="danger" @click="deleteHandles">批量删除</el-button>
			</el-form-item>
		</el-form>
		<el-table
			v-loading="state.dataListLoading"
			:data="state.tableData"
			border
			row-key="tm"
			max-height="calc(100vh - 360px )"
			style="width: 100%"
			@selection-change="useCrud(state).selectionChangeHandle"
		>
			<el-table-column type="selection" width="55" align="center" v-if="!state.queryForm.empiRuleInfoVersion"> </el-table-column>
			<el-table-column type="index" label="序号" width="100" align="center"> </el-table-column>
			<el-table-column prop="fieldCode" label="字段名称" header-align="center" align="center">
				<template #default="scope">
					{{ getFiledName(scope.row.fieldCode) }}
				</template>
			</el-table-column>
			<el-table-column prop="algoCode" label="匹配算法" header-align="center" align="center">
				<template #default="scope">
					{{ getAlgoName(scope.row.algoCode) }}
				</template>
			</el-table-column>
			<el-table-column prop="weight" label="匹配权重（%）" header-align="center" align="center"></el-table-column>

			<el-table-column prop="remark" label="备注" header-align="center" align="center"></el-table-column>
			<el-table-column prop="ifInvalid" label="状态" header-align="center" align="center">
				<template #default="scope">
					{{ scope.row.ifInvalid == 0 ? '开启' : '关闭' }}
					<el-switch
						:disabled="state.queryForm.empiRuleInfoVersion"
						@change="ifInvalidChange($event, scope.row)"
						v-model="scope.row.ifInvalid"
						:active-value="0"
						:inactive-value="1"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200" v-if="!state.queryForm.empiRuleInfoVersion">
				<template #default="scope">
					<el-button type="primary" link @click="addOrUpdateHandle(scope.$index, 'edit', scope.row)">编辑</el-button>
					<el-button type="danger" link @click="deleteHandle(scope.$index)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<AddOrUpdateFieIds ref="addOrUpdateFieIdsRef" @close="getAddOrUpDateData"></AddOrUpdateFieIds>
	</el-drawer>
</template>
<script setup lang="ts">
import { useCrud } from '@/hooks/indexZSYPost.ts'
import { IHooksOptions } from '@/hooks/interface'
import { Delete, Edit, Search, Plus, CircleClose, Refresh, Cellphone } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import AddOrUpdateFieIds from './addOrUpdateFieIds.vue'
import { addRuleField, ruleFieldList } from '@/api/patient-primary/rule-mana'
import { ElMessage, ElMessageBox } from 'element-plus'
import { da } from 'element-plus/es/locale'

const emit = defineEmits(['back', 'close'])

const state: IHooksOptions = reactive({
	dataListUrl: '/empi/empirulefield/page',
	tableData: [],
	queryForm: {
		fieldCode: '',
		ruleId: '',
		ifInvalid: '',
		empiRuleInfoVersion: ''
	},
	limit: 1000,
	dataListSelections: [],
	primaryKey: 'tm'
})

const localData = ref([])

const addOrUpDateData = ref([]) // 新增或修改的数据

const configureVisible = ref(false)

const init = async (verid, id) => {
	state.queryForm.ruleId = id
	state.queryForm.empiRuleInfoVersion = verid
	configureVisible.value = true
	addOrUpDateData.value = []

	getData()
}

const getData = () => {
	state.tableData = []
	ruleFieldList({
		page: 1,
		limit: 1000,
		...state.queryForm
	}).then(res => {
		res.data.list.forEach((item, index) => {
			const data = {
				tm: new Date().getTime() + new Date().getMilliseconds() + index,
				...item
			}
			state.tableData.push(data)
		})
	})
	console.log(state.tableData)
}

const searchEvent = () => {
	addOrUpDateData.value = []
	getData()
}

const ifInvalidChange = (e, data) => {
	data.ifInvalid = e
	addOrUpDateData.value.push(data)
}

const resets = () => {
	state.queryForm.fieldCode = ''
	state.queryForm.ifInvalid = ''

	addOrUpDateData.value = []
	getData()
}

const addOrUpdateFieIdsRef = ref()
const addOrUpdateHandle = (id, type, data) => {
	console.log(state.tableData)
	addOrUpdateFieIdsRef.value.init(id, type, data, state.queryForm.ruleId, state.tableData)
}

const deleteHandle = index => {
	if (state.tableData.length == 1) {
		ElMessage.warning('需至少保留一条字段后再尝试删除，谢谢')
	} else {
		const name = getFiledName(state.tableData[index].fieldCode)

		ElMessageBox.confirm(`确认删除字段【${name}】吗?`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			addOrUpDateData.value.push(state.tableData[index])
			state.tableData?.splice(index, 1)
		})
	}
}

const deleteHandles = () => {
	if (!state.dataListSelections.length) {
		ElMessage.warning('请选择要删除的数据')
	} else {
		console.log(state.dataListSelections)

		if (state.dataListSelections.length == state.tableData.length) {
			ElMessage.warning('需至少保留一条字段后再尝试删除，谢谢')
		} else {
			const delData = state.tableData.filter(item => state.dataListSelections.includes(item.tm))
			console.log(delData)
			let name = ''
			delData.forEach((item, index) => {
				if (index) {
					name = name + ',' + getFiledName(item.fieldCode)
				} else {
					name = getFiledName(item.fieldCode)
				}
			})
			ElMessageBox.confirm(`确认删除字段【${name}】吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				state.dataListSelections.forEach(item => {
					addOrUpDateData.value.push(item)
				})
				state.tableData = state.tableData.filter(item => !state.dataListSelections.includes(item.tm))
			})
		}
	}
}

const getAddOrUpDateData = (data, type, index) => {
	if (type == 'edit') {
		state.tableData[index] = data
		// if (addOrUpDateData.value.length) {
		// 	addOrUpDateData.value[index] = data
		// } else {
		// 	addOrUpDateData.value.push(data)
		// }
	} else {
		state.tableData.push(data)
		// addOrUpDateData.value.push(data)
	}

	state.tableData = JSON.parse(JSON.stringify(state.tableData))
	addOrUpDateData.value.push(data)
}

const backVersion = () => {
	if (!state.queryForm.empiRuleInfoVersion) {
		if (addOrUpDateData.value.length) {
			ElMessageBox.confirm('当前操作未保存，请确认！', '提示', {
				confirmButtonText: '离开',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				addOrUpDateData.value = []
				configureVisible.value = false
				emit('back')
			})
		} else {
			addOrUpDateData.value = []
			configureVisible.value = false
			emit('back')
		}
	} else {
		addOrUpDateData.value = []
		configureVisible.value = false
		emit('back')
	}
}

// 保存
const saveFields = () => {
	if (addOrUpDateData.value.length) {
		state.tableData?.forEach(item => {
			if (item['id'] == undefined) {
			} else {
				delete item.id
			}
		})

		addRuleField(state.tableData).then(() => {
			ElMessage.success('保存成功')
			addOrUpDateData.value = []
			configureVisible.value = false
			emit('close')
		})
	} else {
		ElMessage.success('无修改，不需要保存')
	}
}

const getFiledName = code => {
	let name = ''
	switch (code) {
		case 'ptt_nm':
			name = '患者姓名'
			break
		case 'gdr_cd':
			name = '性别'
			break
		case 'id_crd_no':
			name = '身份证号'
			break
		case 'slf_tel_no':
			name = '手机号'
			break
		case 'bth_dt':
			name = '出生日期'
			break
		case 'address':
			name = '现住址'
			break
	}

	return name
}

const getAlgoName = index => {
	let name = ''
	switch (index) {
		case '1':
			name = '余弦相似度'
			break
		case '2':
			name = '精准匹配'
			break
	}

	return name
}

defineExpose({
	init
})
</script>
<style lang="scss" scoped></style>
